package devcontainer

import (
	gitea_web_module "code.gitea.io/gitea/modules/web"
	Result "code.gitea.io/gitea/routers/entity"
	gitea_web_context "code.gitea.io/gitea/services/context"
	devcontainer_api_service "code.gitea.io/gitea/services/devstar_devcontainer/api_services"
	devcontainer_service_options "code.gitea.io/gitea/services/devstar_devcontainer/options"
	"code.gitea.io/gitea/services/forms"
	"strconv"
)

// CreateRepoDevcontainer 创建 某用户在某仓库的 DevContainer
//
// POST /api/devcontainer
// 请求体参数：
// -- repoId: 需要为哪个仓库创建 DevContainer
// -- sshPublicKeyList: 列表，填入用户希望临时使用的SSH会话加密公钥
// 注意：必须携带 用户登录凭证
func CreateRepoDevcontainer(ctx *gitea_web_context.Context) {

	// 1. 检查用户登录状态，若未登录则返回未授权错误
	if ctx == nil || ctx.Doer == nil {
		Result.RespUnauthorizedFailure.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 2. 检查表单校验规则是否失败
	if ctx.HasError() {
		// POST Binding 表单正则表达式校验失败，返回 API 错误信息
		failedToValidateFormData := &Result.ResultType{
			Code: Result.RespFailedIllegalParams.Code,
			Msg:  Result.RespFailedIllegalParams.Msg,
			Data: map[string]string{
				"ErrorMsg": ctx.GetErrMsg(),
			},
		}
		failedToValidateFormData.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 3. 解析 repoId
	form := gitea_web_module.GetForm(ctx).(*forms.CreateRepoDevcontainerForm)
	repoId, err := strconv.ParseInt(form.RepoId, 10, 64)
	if err != nil || repoId <= 0 {
		failedToParseRepoId := Result.ResultType{
			Code: Result.RespFailedIllegalParams.Code,
			Msg:  Result.RespFailedIllegalParams.Msg,
			Data: map[string]string{
				// fix nullptr dereference of `err.Error()` when repoId == 0
				"ErrorMsg": "repoId 必须是正数",
			},
		}
		failedToParseRepoId.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 4. 调用 API Service 层创建 DevContainer
	opts := &devcontainer_service_options.CreateDevcontainerOptions{
		Actor:            ctx.Doer,
		RepoId:           repoId,
		SSHPublicKeyList: form.SSHPublicKeyList,
	}
	err = devcontainer_api_service.CreateDevcontainerAPIService(ctx, opts)
	if err != nil {
		errCreateDevcontainer := Result.ResultType{
			Code: Result.RespFailedCreateDevcontainer.Code,
			Msg:  Result.RespFailedCreateDevcontainer.Msg,
			Data: map[string]string{
				"ErrorMsg": err.Error(),
			},
		}
		errCreateDevcontainer.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 4. 创建 DevContainer 成功，直接返回
	Result.RespSuccess.RespondJson2HttpResponseWriter(ctx.Resp)
}
